package cn.doitedu.hbase.hbasemr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import java.io.IOException;


/**
 * @date: 2019/8/18
 * @site: www.doitedu.cn
 * @author: hunter.d 涛哥
 * @qq: 657270652
 * @description:
 *
 *     数据源： hdfs文件
 *     目标存储： hbase
 */
public class ReadHDFS2Hbase {

    public static class M extends Mapper<LongWritable, Text,Text, IntWritable>{

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {


            String[] words = value.toString().split(" ");
            for (String word : words) {
                context.write(new Text(word),new IntWritable(1));
            }
        }
    }


    // ImmutableBytesWritable是reduce阶段输出的value的类型，它的具体实现就是一个put(内含行键，及各个kv）
    public static class R extends TableReducer<Text,IntWritable, ImmutableBytesWritable>{


        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int count = 0;
            for (IntWritable value : values) {
                count += value.get();
            }

            Put put = new Put(key.toString().getBytes());
            put.addColumn("f".getBytes(),"cnt".getBytes(), Bytes.toBytes(count));


            context.write(new ImmutableBytesWritable(key.toString().getBytes()),put);
        }
    }

    public static void main(String[] args) throws Exception {


        Configuration conf = new Configuration();
        conf.set("hbase.zookeeper.quorum","spark01:2181,spark02:2181,spark03:2181");

        Job job = Job.getInstance(conf);


        job.setJarByClass(ReadHDFS2Hbase.class);

        job.setMapperClass(M.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);


        job.setNumReduceTasks(1);

        // 使用hbase提供的工具来设置输出outputformat为TableOutputFormat，以及指定目标表名称
        TableMapReduceUtil.initTableReducerJob("wc",R.class,job);

        // 设置自己的文件输入路径
        FileInputFormat.setInputPaths(job,new Path("data/wcinput/"));


        job.waitForCompletion(true);



    }




}
